package com.glsc.ngateway.platform.controller.dev;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.excel.util.CollectionUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.glsc.ngateway.common.api.common.dto.PageDataResult;
import com.glsc.ngateway.common.api.common.utils.CommonUtils;
import com.glsc.ngateway.common.api.common.utils.DateUtil;
import com.glsc.ngateway.common.api.common.utils.JsonUtil;
import com.glsc.ngateway.common.api.common.utils.PageUtil;
import com.glsc.ngateway.common.api.flowable.dto.demand.*;
import com.glsc.ngateway.common.api.flowable.dto.demand.node.ProcessNode;
import com.glsc.ngateway.common.api.flowable.dto.param.ParamCommentDto;
import com.glsc.ngateway.common.api.flowable.dto.param.ParamCreateDto;
import com.glsc.ngateway.common.api.flowable.dto.param.ParamDoTaskDto;
import com.glsc.ngateway.common.api.flowable.dto.param.ParamSearchDto;
import com.glsc.ngateway.common.api.flowable.feign.IFeignFlowableService;
import com.glsc.ngateway.common.api.flowable.resp.*;
import com.glsc.ngateway.common.api.ldap.dto.LdapEhrDeptDto;
import com.glsc.ngateway.common.api.ldap.dto.LdapEhrDeptSearchDto;
import com.glsc.ngateway.common.api.ldap.dto.LdapEhrEmpDto;
import com.glsc.ngateway.common.api.ldap.dto.LdapUserDto;
import com.glsc.ngateway.common.api.ldap.feign.IFeignLdapService;
import com.glsc.ngateway.common.api.ldap.resp.AppEhrResponse;
import com.glsc.ngateway.common.api.ldap.resp.LdapResponse;
import com.glsc.ngateway.common.api.oaflow.feign.IFeignOaFlowService;
import com.glsc.ngateway.common.api.platform.dto.user.PlatformUserDto;
import com.glsc.ngateway.common.api.platform.resp.PlatformResponse;
import com.glsc.ngateway.common.api.shortmsg.bo.MessageGenericVo;
import com.glsc.ngateway.common.api.shortmsg.feign.IFeignShortmsgService;
import com.glsc.ngateway.common.base.domain.mysql.gateway.other.SystemConfig;
import com.glsc.ngateway.common.base.domain.mysql.gateway.platform.MysqlDataDictionary;
import com.glsc.ngateway.common.base.dto.oaecology.OaDemandFlowSumDto;
import com.glsc.ngateway.common.base.dto.oaecology.OaDemandFlowSumQueryDto;
import com.glsc.ngateway.common.base.enums.OaHrmresourceStatusEnum;
import com.glsc.ngateway.common.base.exception.PlatformException;
import com.glsc.ngateway.common.base.repo.mysql.gateway.platform.MysqlDataDictionaryRepository;
import com.glsc.ngateway.platform.aspect.UserCache;
import com.glsc.ngateway.platform.service.dev.DemandService;
import com.glsc.ngateway.platform.service.SystemConfigService;
import com.glsc.ngateway.platform.service.UserService;
import com.glsc.ngateway.platform.service.gitee.GiteeService;
import com.glsc.ngateway.platform.service.oaecology.OaDemandFlowSumService;
import com.glsc.ngateway.platform.utils.AssertOverride;
import com.glsc.ngateway.platform.utils.RequestTool;
import com.glsc.ngateway.platform.utils.TokenUtil;
import com.glsc.ngateway.platform.utils.report.ReportFileConfigEnum;
import com.glsc.ngateway.platform.utils.report.ReportFileUtil;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableList;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@RestController
@RequestMapping(value = "/demand")
public class DemandManagementController {
    Logger logger = LoggerFactory.getLogger(this.getClass());
    private static int default_page_number = 1;
    private static int default_page_size = 10;
    private static String no_result = "noResult";
    @Resource
    IFeignFlowableService feignDemandService;
    @Resource
    IFeignLdapService feignLdapService;
    @Resource
    IFeignOaFlowService feignOaflowService;
    @Resource
    private GiteeService giteeService;
    @Autowired
    DemandService demandService;
    @Autowired
    TokenUtil tokenUtil;
    @Value("${demand.downloadUrl}")
    private String downloadUrl;
    @Resource
    private IFeignShortmsgService shortmsgService;
    @Resource
    private UserService userService;
    @Resource
    private RequestTool requestTool;
    @Autowired
    private UserCache userCache;
    @Resource
    private MysqlDataDictionaryRepository mysqlDataDictionaryRepository;
    @Resource
    private SystemConfigService configService;

    @Resource
    private OaDemandFlowSumService oaDemandFlowSumService;

    @RequestMapping(method = RequestMethod.GET, value = "getOaUserToken")
    public PlatformResponse<String> getOaUserToken(@RequestParam(value = "userId", required = true) String userId,
                                                   @RequestParam(value = "systemId", required = true) String systemId) {
        try {
            String result = feignLdapService.getOaUserToken(LdapUserDto.builder()
                    .userName(userId)
                    .systemId(systemId)
                    .build());
            return PlatformResponse.successData(result);
        } catch (Exception e) {
            logger.error("getOaUserToken异常！", e);
            return PlatformResponse.failedMsg("操作失败", e.getMessage());
        }
    }


    @RequestMapping(method = RequestMethod.GET, value = "getUserInfo")
    public PlatformResponse<DemandManagementDto> getUserInfo(@RequestParam(value = "userId", required = true) String userId) {
        PlatformResponse<DemandManagementDto> ret = null;
        try {
            DemandManagementDto glRequirement = new DemandManagementDto();
            glRequirement.setRqStaff(userId);
            AppEhrResponse<LdapEhrEmpDto> user = feignLdapService.getLdapEhrEmp(userId, null, false);
            //废弃admin和itadmin，对逻辑无影响
            if (("admin").equals(userId) || ("itadmin").equals(userId) || ("devadmin").equals(userId)) {
                glRequirement.setRqDepartment("信息技术总部");
                glRequirement.setRqStaffCName("系统管理员");
            } else {
                if (user != null) {
                    LdapEhrEmpDto map = user.getData();
                    glRequirement.setRqDepartment(map.getTitle());
                    glRequirement.setRqStaffCName(map.getName());
                }
            }
            ret = PlatformResponse.successData(glRequirement);

        } catch (Exception e) {
            ret = PlatformResponse.failedMsg("操作失败", e.getMessage());
            logger.error("getUserInfo异常！", e);
        }
        return ret;
    }

    private Object map2JavaBean(Class<?> clazz, Map<String, String> map) throws Exception {
        Object javabean = clazz.newInstance(); // 构建对象
        Method[] methods = clazz.getMethods(); // 获取所有方法
        for (Method method : methods) {
            if (method.getName().startsWith("set")) {
                String field = method.getName(); // 截取属性名
                field = field.substring(field.indexOf("set") + 3);
                field = field.toLowerCase().charAt(0) + field.substring(1);
                if (map.containsKey(field)) {
                    method.invoke(javabean, map.get(field));
                }
            }
        }
        return javabean;
    }

    @RequestMapping(method = RequestMethod.GET, value = "getUserList")
    public PlatformResponse<List<ResponseUserListDto>> getUserList(
            @RequestParam(value = "department", required = false) String department,
            @RequestParam(value = "findAll", required = false) boolean findAll
    ) {
        try {
            AppEhrResponse<List<LdapEhrEmpDto>> user = feignLdapService.getAllEmps();
            if (Objects.isNull(user) || CollectionUtil.isEmpty(user.getData())) {
                return PlatformResponse.successData(Collections.EMPTY_LIST);
            }
            //过滤在职人员
            if (!findAll) {
                user.setData(user.getData().stream().filter(u -> OaHrmresourceStatusEnum.isAlive(u.getStatus())).collect(Collectors.toList()));
            }
            if (CollectionUtil.isEmpty(user.getData())) {
                return PlatformResponse.successData(Collections.EMPTY_LIST);
            }
            //获取所有部门
            AppEhrResponse<List<LdapEhrDeptDto>> depts = feignLdapService.getAllDept();
            if (Objects.isNull(depts) || CollectionUtil.isEmpty(depts.getData())) {
                return PlatformResponse.successData(Collections.EMPTY_LIST);
            }
            //支持多级部门
            Set<String> depSet;
            if (StringUtils.isBlank(department)) {
                depSet = depts.getData().stream()
                        .map(LdapEhrDeptDto::getDtitle)
                        .collect(Collectors.toSet());
            } else {
                depSet = new HashSet<>();
                Map<String, List<LdapEhrDeptDto>> parentMap = depts.getData().stream()
                        .filter(d -> StringUtils.isNotBlank(d.getAtitle()))
                        .collect(Collectors.groupingBy(LdapEhrDeptDto::getAtitle));
                //bfs筛选
                Queue<LdapEhrDeptDto> que = new LinkedList<>(parentMap.get(department));
                while (!que.isEmpty()) {
                    LdapEhrDeptDto poll = que.poll();
                    depSet.add(poll.getDtitle());
                    if (parentMap.containsKey(poll.getDtitle())) {
                        que.addAll(parentMap.get(poll.getDtitle()));
                    }
                }
            }
            Map<Integer, List<LdapEhrEmpDto>> userMap = user.getData()
                    .stream()
                    .filter(e -> !StringUtils.isEmpty(e.getTitle()) && Objects.nonNull(e.getDepid())
                            && (StringUtils.isEmpty(department) || depSet.contains(e.getTitle())))
                    .collect(Collectors.groupingBy(LdapEhrEmpDto::getDepid));

            Map<Integer, LdapEhrDeptDto> deptMap = depts.getData().stream().collect(Collectors.toMap(LdapEhrDeptDto::getDepid, Function.identity(), (K1, K2) -> K2));
            List<ResponseUserListDto> reslist = userMap.entrySet().stream()
                    .map(m -> {
                        if (!deptMap.containsKey(m.getKey())) {
                            return null;
                        }
                        LdapEhrDeptDto deptinfoEntity = deptMap.get(m.getKey());
                        ResponseUserListDto res = new ResponseUserListDto();
                        res.setTitle(deptinfoEntity.getDtitle());
                        res.setValue(String.valueOf(deptinfoEntity.getDepid()));
                        res.setKey(String.valueOf(deptinfoEntity.getDepid()));
                        List<ResponseUserListSubDto> list = m.getValue().stream()
                                .map(f -> ResponseUserListSubDto.builder()
                                        .title(f.getName())
                                        .value(f.getBadge())
                                        .key(f.getBadge())
                                        .department(deptinfoEntity.getDtitle())
                                        .departmentValue(res.getValue())
                                        .build())
                                .sorted(Comparator.comparing(ResponseUserListSubDto::getTitle))
                                .collect(Collectors.toList());
                        res.setChildren(list);
                        return res;
                    })
                    .filter(Objects::nonNull)
                    .sorted(Comparator.comparing(ResponseUserListDto::getTitle))
                    .collect(Collectors.toList());
            return PlatformResponse.successData(reslist);
        } catch (Exception e) {
            logger.error("getUserList异常！", e);
            return PlatformResponse.failedMsg("操作失败", e.getMessage());
        }
    }

    @SneakyThrows
    @RequestMapping(method = RequestMethod.GET, value = "getDepartmentList")
    public PlatformResponse<JSONArray> getDepartmentList(@RequestParam(value = "department", required = false) String department,
                                                         @RequestParam(value = "groupBy", required = false) String groupBy,
                                                         @RequestParam(value = "findAll", required = false) boolean findAll ){
        AppEhrResponse<List<LdapEhrDeptDto>> depts = feignLdapService.getAllDept();
        //过滤无效
        if (!findAll) {
            depts.setData(depts.getData().stream().filter(u -> !"1".equals(u.getCanceled())).collect(Collectors.toList()));
        }
        if (Objects.isNull(depts) || CollectionUtil.isEmpty(depts.getData())) {
            return PlatformResponse.successData(new JSONArray());
        }
        return PlatformResponse.successData(userService.convertToTreeJson(depts.getData(), department, groupBy));
    }

    @SneakyThrows
    @RequestMapping(method = RequestMethod.POST, value = "queryDept")
    public PlatformResponse<List<LdapEhrDeptDto>> queryDept(@RequestBody LdapEhrDeptSearchDto param){
        LdapResponse<List<LdapEhrDeptDto>> resp = feignLdapService.getDepartmentList(param);
        return PlatformResponse.successData(resp.getData());
    }



    /**
     * 创建一个新的需求
     *
     * @param request
     * @param glRequirement
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "createRq")
    public PlatformResponse<String> createRq(HttpServletRequest request, @RequestBody DemandManagementDto glRequirement) {
        PlatformResponse<String> ret;
        AssertOverride.notNull(glRequirement.getRqStaff(), "创建人员为空，请刷新页面重试或联系管理员");
        try {
            //1.调用网关系统启动流程，并存储需求,所有需求都只记录在网关系统
            ParamCreateDto paramCreateDto = new ParamCreateDtoBuilder().setReqStartElemets(glRequirement).build();
            FlowableResponse<ResponseCreateDto> creatflowRet = feignDemandService.create(paramCreateDto);
            if (creatflowRet.getStatus() == 0) {
                notify(creatflowRet.getData().getProcessId());
                return PlatformResponse.successData(creatflowRet.getData().getProcessId());
            } else {
                return PlatformResponse.failedMsg("操作失败", creatflowRet.getMsg());
            }
        } catch (Exception e) {
            logger.error("createRq异常！", e);
            return PlatformResponse.failedMsg("操作失败", e.getMessage());
        }
    }

    @GetMapping("/notify")
    public void notify(@RequestParam("processId") String processId) {
        notify(processId, null);
    }

    private void notify(String processId, PassFlag passFlag) {
        try {
            SystemConfig agentIdConfig = configService.findByCode("WECHAT_GATEWAY_APP_AGENTID");
            if (Objects.isNull(agentIdConfig) || org.apache.logging.log4j.util.Strings.isBlank(agentIdConfig.getConfigValue())) {
                logger.error("需求流程提醒异常：缺少配置WECHAT_GATEWAY_APP_AGENTID");
            }
            FlowableResponse<ResponseSituationDto> procResp = feignDemandService.getProcessInfo(processId);
            if (Objects.isNull(procResp) || Objects.isNull(procResp.getData())) {
                logger.error("需求流程提醒，未找到需求流程pid：{}", processId);
                return;
            }
            ResponseSituationDto data = procResp.getData();
            if (Strings.isNullOrEmpty(data.getCurrentAssignee())) {
                logger.error("需求流程提醒，当前无待办人pid：{}", processId);
            }
            List<String> curAcc = Arrays.stream(data.getCurrentAssignee().split("\\|")).collect(Collectors.toList());
            Map<String, String> systemMap = mysqlDataDictionaryRepository.findByFieldName("SYSTEM_ID").stream().collect(Collectors.toMap(MysqlDataDictionary::getfCode, MysqlDataDictionary::getfValues));
            shortmsgService.sendAgentMessageGeneric(MessageGenericVo.builder()
                    .oaUserAccounts(curAcc)
                    .agentId(agentIdConfig.getConfigValue())
                    .textContent("【国联技术服务平台提醒】" + ((Objects.isNull(passFlag) || passFlag.isPass()) ? "您有新的待办" : "您有流程被驳回") +
                            "<br>" + systemMap.getOrDefault(data.getSysid(), StringUtils.EMPTY) +
                            "，需求：" + data.getProcessTitle() +
                            "，需求提出人：" + data.getStartUserChineseName() +
                            "，处理节点：" + data.getCurrentTaskName() +
                            "，请您及时登录系统进行处理。")
                    .build());
        } catch (Exception ex) {
            logger.error("企微通知失败", ex);
        }
    }


    private String getFlowableErrMsg(FlowableResponse nwret) {
        StringBuilder sb = new StringBuilder("Flowable异常：");
        sb.append(nwret.getMsg());
        if (nwret.getData() != null && nwret.getData() instanceof ResponseMsgDto) {
            sb.append("---").append(((ResponseMsgDto) nwret.getData()).getMsg());
        }
        return sb.toString();
    }


    /**
     * "需求提交"节点操作
     *
     * @param request
     * @param glRequirement
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "submitTask")
    public PlatformResponse<?> submitTask(HttpServletRequest request, @RequestBody DemandManagementDto glRequirement) {
        PlatformResponse<?> ret;
        try {
            //根据processId获取当前节点taskId
            String[] taskIdAndTitleAndSysid = demandService.getCurrentTaskIdAndTitleAndSysid(glRequirement.getRqId());
            if (taskIdAndTitleAndSysid == null) {
                ret = PlatformResponse.failedMsg("未获取到当前流程节点信息");
            }

            ParamDoTaskDto nwreq = new ParamDoTaskDtoBuilder(taskIdAndTitleAndSysid[0], taskIdAndTitleAndSysid[1], taskIdAndTitleAndSysid[2]).setSubmit(glRequirement).build();

            FlowableResponse<ResponseMsgDto> nwret = feignDemandService.doTask(nwreq);
            if (nwret.getStatus() != 0) {
                ret = PlatformResponse.failedMsg("操作失败", getFlowableErrMsg(nwret));
            } else {
                notify(glRequirement.getRqId());
                ret = PlatformResponse.success();
            }

        } catch (Exception e) {
            ret = PlatformResponse.failedMsg("操作失败", e.getMessage());
            logger.error("submitTask异常！", e);
        }

        return ret;
    }


    /**
     * "需求确认"节点操作
     */
    @RequestMapping(method = RequestMethod.POST, value = "confirmTask")
    public PlatformResponse<?> confirmTask(HttpServletRequest request, @RequestBody ConfirmTaskReq passConfirmReq) {
        PlatformResponse<?> ret;
        try {
            //根据processId获取当前节点taskId
            ResponseSituationDto processInfo = demandService.getProcessInfo(passConfirmReq.getRqId());
            if (processInfo == null) {
                ret = PlatformResponse.failedMsg("未获取到当前流程节点信息");
            }

            ParamDoTaskDto nwreq = new ParamDoTaskDtoBuilder(processInfo.getCurrentTaskId(), processInfo.getProcessTitle(), processInfo.getSysid()).setConfirmTask(passConfirmReq).build();

            FlowableResponse<ResponseMsgDto> nwret = feignDemandService.doTask(nwreq);
            if (nwret.getStatus() != 0) {
                ret = PlatformResponse.failedMsg("操作失败", getFlowableErrMsg(nwret));
            } else {
                notify(passConfirmReq.getRqId(), passConfirmReq.getPassFlag());
                ret = PlatformResponse.success();
                giteeService.addGiteeDemand(processInfo, passConfirmReq);
            }
        } catch (Exception e) {
            ret = PlatformResponse.failedMsg("操作失败", e.getMessage());
            logger.error("confirmTask异常！", e);
        }
        return ret;
    }


    /**
     * "高级审批"节点操作
     */
    @RequestMapping(method = RequestMethod.POST, value = "advanceTask")
    public PlatformResponse<?> advanceTask(HttpServletRequest request, @RequestBody AdvanceTaskReq advanceTaskReq) {
        PlatformResponse<?> ret;
        try {
            //根据processId获取当前节点taskId

            String[] taskIdAndTitle = demandService.getCurrentTaskIdAndTitleAndSysid(advanceTaskReq.getRqId());
            if (taskIdAndTitle == null) {
                ret = PlatformResponse.failedMsg("未获取到当前流程节点信息");
            }

            ParamDoTaskDto nwreq = new ParamDoTaskDtoBuilder(taskIdAndTitle[0], taskIdAndTitle[1], taskIdAndTitle[2]).setAdvanceTask(advanceTaskReq).build();

            FlowableResponse<ResponseMsgDto> nwret = feignDemandService.doTask(nwreq);
            if (nwret.getStatus() != 0) {
                ret = PlatformResponse.failedMsg("操作失败", getFlowableErrMsg(nwret));
            } else {
                notify(advanceTaskReq.getRqId(), advanceTaskReq.getPassFlag());
                ret = PlatformResponse.success();
            }

        } catch (Exception e) {
            ret = PlatformResponse.failedMsg("操作失败", e.getMessage());
            logger.error("advanceTask异常！", e);
        }

        return ret;
    }


    /**
     * "相关人员会签"节点操作
     */
    @RequestMapping(method = RequestMethod.POST, value = "signatureTask")
    public PlatformResponse<?> signatureTask(HttpServletRequest request, @RequestBody SignatureTaskReq signatureTaskReq) {
        PlatformResponse<?> ret;
        try {
            //根据processId获取当前节点taskId
            String[] taskIdAndTitle = demandService.getCurrentTaskIdAndTitleAndSysid(signatureTaskReq.getRqId());
            if (taskIdAndTitle == null) {
                ret = PlatformResponse.failedMsg("未获取到当前流程节点信息");
            }

            ParamDoTaskDto nwreq = new ParamDoTaskDtoBuilder(signatureTaskReq.getTaskId(), taskIdAndTitle[1], taskIdAndTitle[2]).setSignatureTask(signatureTaskReq).build();

            FlowableResponse<ResponseMsgDto> nwret = feignDemandService.doTask(nwreq);
            if (nwret.getStatus() != 0) {
                ret = PlatformResponse.failedMsg("操作失败", getFlowableErrMsg(nwret));
            } else {
                notify(signatureTaskReq.getRqId());
                ret = PlatformResponse.success();
            }

        } catch (Exception e) {
            ret = PlatformResponse.failedMsg("操作失败", e.getMessage());
            logger.error("signatureTask异常！", e);
        }

        return ret;
    }


    /**
     * "OA会签"节点操作
     */
    @RequestMapping(method = RequestMethod.POST, value = "createoaTask")
    public PlatformResponse<?> createoaTask(HttpServletRequest request, @RequestBody CreateoaTaskReq createoaTaskReq) {
        PlatformResponse<?> ret;
        try {
            //根据processId获取当前节点taskId
            String[] taskIdAndTitle = demandService.getCurrentTaskIdAndTitleAndSysid(createoaTaskReq.getRqId());
            if (taskIdAndTitle == null) {
                ret = PlatformResponse.failedMsg("未获取到当前流程节点信息");
            }

            ParamDoTaskDto nwreq = new ParamDoTaskDtoBuilder(taskIdAndTitle[0], taskIdAndTitle[1], taskIdAndTitle[2]).setCreateoaTask(createoaTaskReq).build();

            FlowableResponse<ResponseMsgDto> nwret = feignDemandService.doTask(nwreq);
            if (nwret.getStatus() != 0) {
                ret = PlatformResponse.failedMsg("操作失败", getFlowableErrMsg(nwret));
            } else {
                notify(createoaTaskReq.getRqId());
                ret = PlatformResponse.success();
            }

        } catch (Exception e) {
            ret = PlatformResponse.failedMsg("操作失败", e.getMessage());
            logger.error("createoaTask异常！", e);
        }

        return ret;
    }


    /**
     * "排期"节点操作
     */
    @RequestMapping(method = RequestMethod.POST, value = "arrangeTask")
    public PlatformResponse<?> arrangeTask(HttpServletRequest request, @RequestBody ArrangeTaskReq arrangeTaskReq) {
        PlatformResponse<?> ret;
        try {
            //根据processId获取当前节点taskId

            String[] taskIdAndTitle = demandService.getCurrentTaskIdAndTitleAndSysid(arrangeTaskReq.getRqId());
            if (taskIdAndTitle == null) {
                ret = PlatformResponse.failedMsg("未获取到当前流程节点信息");
            }

            ParamDoTaskDto nwreq = new ParamDoTaskDtoBuilder(taskIdAndTitle[0], taskIdAndTitle[1], taskIdAndTitle[2]).setArrangeTaskReq(arrangeTaskReq).build();

            FlowableResponse<ResponseMsgDto> nwret = feignDemandService.doTask(nwreq);
            if (nwret.getStatus() != 0) {
                ret = PlatformResponse.failedMsg("操作失败", getFlowableErrMsg(nwret));
            } else {
                notify(arrangeTaskReq.getRqId());
                giteeService.addGiteeTask(arrangeTaskReq);
                ret = PlatformResponse.success();
            }

        } catch (Exception e) {
            ret = PlatformResponse.failedMsg("操作失败", e.getMessage());
            logger.error("arrangeTask异常！", e);
        }

        return ret;
    }


    @RequestMapping(method = RequestMethod.GET, value = "syncAllIssueeScheduled")
    public void syncAllIssueeScheduled() {
        giteeService.syncAllIssueScheduled();
    }

    @RequestMapping(method = RequestMethod.GET, value = "syncGiteeIssuee")
    public void syncGiteeIssuee() {
        giteeService.syncGiteeIssue();
    }

    /**
     * "上线"节点操作
     */
    @RequestMapping(method = RequestMethod.POST, value = "onlineTask")
    public PlatformResponse<?> onlineTask(HttpServletRequest request, @RequestBody OnlineTaskReq onlineTaskReq) {
        PlatformResponse<?> ret;
        try {
            logger.info("onlineTaskReq{}",onlineTaskReq);
            //根据processId获取当前节点taskId
            String[] taskIdAndTitle = demandService.getCurrentTaskIdAndTitleAndSysid(onlineTaskReq.getRqId());
            if (taskIdAndTitle == null) {
                ret = PlatformResponse.failedMsg("未获取到当前流程节点信息");
            }

            //有可能有的开发人员已经处理过该节点，需要把上线要素进行合并
            FlowableDemandDto rqmt = demandService.getRmptInfo(onlineTaskReq.getRqId());
            List<OnlineInf> oldinfo = new ArrayList<OnlineInf>();
            if (!StringUtils.isEmpty(rqmt.getOnlineinfo())) {
                oldinfo = (List<OnlineInf>) JsonUtil.str2Obj(rqmt.getOnlineinfo(), List.class);
            }

            ParamDoTaskDto nwreq = new ParamDoTaskDtoBuilder(onlineTaskReq.getTaskId(), taskIdAndTitle[1], taskIdAndTitle[2]).setOnlineTaskReq(oldinfo, onlineTaskReq).build();

            FlowableResponse<ResponseMsgDto> nwret = feignDemandService.doTask(nwreq);
            if (nwret.getStatus() != 0) {
                ret = PlatformResponse.failedMsg("操作失败", getFlowableErrMsg(nwret));
            } else {
                notify(onlineTaskReq.getRqId());
                ret = PlatformResponse.success();
            }

        } catch (Exception e) {
            logger.error("onlineTask异常！", e);
            ret = PlatformResponse.failedMsg("操作失败", e.getMessage());
        }

        return ret;
    }


    /**
     * "验证"节点操作
     */
    @RequestMapping(method = RequestMethod.POST, value = "checkTask")
    public PlatformResponse<?> checkTask(HttpServletRequest request, @RequestBody CheckTaskReq checkTaskReq) {
        PlatformResponse<?> ret;
        try {
            //根据processId获取当前节点taskId

            String[] taskIdAndTitle = demandService.getCurrentTaskIdAndTitleAndSysid(checkTaskReq.getRqId());
            if (taskIdAndTitle == null) {
                ret = PlatformResponse.failedMsg("未获取到当前流程节点信息");
            }

            ParamDoTaskDto nwreq = new ParamDoTaskDtoBuilder(taskIdAndTitle[0], taskIdAndTitle[1], taskIdAndTitle[2]).setCheckTaskReq(checkTaskReq).build();

            FlowableResponse<ResponseMsgDto> nwret = feignDemandService.doTask(nwreq);
            if (nwret.getStatus() != 0) {
                ret = PlatformResponse.failedMsg("操作失败", getFlowableErrMsg(nwret));
            } else {
                notify(checkTaskReq.getRqId());
                ret = PlatformResponse.success();
            }

        } catch (Exception e) {
            ret = PlatformResponse.failedMsg("操作失败", e.getMessage());
            logger.error("checkTask异常！", e);
        }
        return ret;
    }


    /**
     * @param request
     * @param pageNumber
     * @param pageSize
     * @param userId        用户
     * @param rqListType    需求结果集类型
     * @param title         过滤条件：需求标题
     * @param beginDate     过滤条件：需求创建日期
     * @param endDate       过滤条件：需求创建日期
     * @param finishFlag    过滤条件：需求是否结束 0：已结束  1：未结束
     * @param createProject 系统
     * @return
     */
    @RequestMapping(method = RequestMethod.GET, value = "listRq")
    public PlatformResponse<Page<DemandManagementDto>> listRq(
            HttpServletRequest request,
            @RequestParam(value = "pageNumber", required = false) Integer pageNumber,
            @RequestParam(value = "pageSize", required = false) Integer pageSize,
            @RequestParam(value = "userId", required = false) String userId,
            @RequestParam(value = "demandDetail", required = false) String demandDetail,
            @RequestParam(value = "showSameDepartment", required = false) String showSameDepartment,
            @RequestParam(value = "rqListType", required = false) RqListType rqListType,
            @RequestParam(value = "title", required = false) String title,
            @RequestParam(value = "beginDate", required = false) String beginDate,
            @RequestParam(value = "endDate", required = false) String endDate,
            @RequestParam(value = "finishFlag", required = false) String finishFlag,
            @RequestParam(value = "createProject", required = false) String createProject,
            @RequestParam(value = "vcStaff", required = false) String vcStaff,
            @RequestParam(value = "vcOriginalStaff", required = false) String vcOriginalStaff,
            @RequestParam(value = "devUserId", required = false) String devUserId,
            @RequestParam(value = "dealUser", required = false) String dealUser,
            @RequestParam(value = "archived", required = false) Boolean archived
    ) {
        PlatformUserDto userDto = userCache.get(request);
        logger.info("通过token获取当前用户账户:{}", userDto);

        pageNumber = PageUtil.initPageNo(pageNumber);
        pageSize = PageUtil.initPageSize(pageSize);

        if (StringUtils.isNotEmpty(finishFlag)) {//是否结束，前端数据：1-未完成
            int finishInt = Integer.parseInt(finishFlag);
            finishInt = 1 - finishInt;
            finishFlag = String.valueOf(finishInt);
        }

        PlatformResponse<Page<DemandManagementDto>> ret;

        ParamSearchDto paramSearchDto =
                new ParamSearchDtoBuilder(rqListType, createProject, userId)
                        .setTitle(title)
                        .setBeginDate(DateUtil.getLocalDate(beginDate))
                        .setEndDate(DateUtil.getLocalDate(endDate))
                        .setHasProcessEnd(finishFlag)
                        .setArchived(archived)
                        .build();

        try {
            /**涉及到跨库查询，进过和志鹏讨论不做合库查询，用processlist作为限制条件
             */
            if (StringUtils.isNotEmpty(dealUser)) {//筛选流程当前处理人
                FlowableResponse<List<String>> dealUserListResponse = feignDemandService.queryProcessListByCurrentAssignee(dealUser, paramSearchDto.getProcessDefineKey(), createProject);
                List<String> dealUserProcessList = dealUserListResponse.getData();
                if (CollectionUtil.isNotEmpty(dealUserProcessList)) {
                    if (CollectionUtil.isEmpty(paramSearchDto.getProcessIdList())) {
                        paramSearchDto.setProcessIdList(dealUserProcessList);
                    } else {
                        paramSearchDto.getProcessIdList().addAll(dealUserProcessList);
                    }
                } else {
                    //查询为空，让流程引擎搜索不到
                    paramSearchDto.setProcessIdList(ImmutableList.of(no_result));
                }
            }

            //表单要素筛选：需求人、原始需求人等表单要素
            List<String> sameDepartmentAccounts = new ArrayList<>();//同组人员发起的流程也能够查看
            if (StringUtils.isNotEmpty(vcStaff) || StringUtils.isNotEmpty(vcOriginalStaff) || StringUtils.isNotEmpty(devUserId)
                    || StringUtils.isNotEmpty(demandDetail) || StringUtils.isNotEmpty(showSameDepartment)) {
                if (StringUtils.isNotEmpty(showSameDepartment)) {//同组人员发起的流程也能够查看
                    AppEhrResponse<List<LdapEhrEmpDto>> depts = feignLdapService.getEmpsByDepts(ImmutableList.of(userDto.getDepartment()));
                    sameDepartmentAccounts = depts.getData().stream().map(LdapEhrEmpDto::getBadge).collect(Collectors.toList());
                }
                FlowableResponse<List<FlowableDemandDto>> demandListResponse = feignDemandService.findByVcStaffLikeOrVcOriginalStaffOrDevUserId(vcStaff, vcOriginalStaff, devUserId, sameDepartmentAccounts, demandDetail);
                List<FlowableDemandDto> demandList = demandListResponse.getData();
                List<String> deamProcessList = demandList.stream().map(FlowableDemandDto::getProcessInstanceId).collect(Collectors.toList());
                if (CollectionUtil.isNotEmpty(deamProcessList)) {
                    if (CollectionUtil.isEmpty(paramSearchDto.getProcessIdList())) {
                        paramSearchDto.setProcessIdList(deamProcessList);
                    } else if (paramSearchDto.getProcessIdList().stream().noneMatch(e -> e.equals(no_result))) {
                        paramSearchDto.getProcessIdList().addAll(deamProcessList);
                    }
                } else {
                    paramSearchDto.setProcessIdList(ImmutableList.of(no_result));
                }
            }

            FlowableResponse<PageDataResult<ResponseSituationDto>> queryflowRet;


            if (RqListType.TODO.equals(rqListType)) {//待办
                queryflowRet = feignDemandService.searchDealProcessList(pageNumber, pageSize, paramSearchDto);
            } else if (RqListType.MINE.equals(rqListType)) {//我发起的
                queryflowRet = feignDemandService.searchAllOrStartProcessList(pageNumber, pageSize, paramSearchDto);
            } else if (RqListType.RELATED.equals(rqListType)) {//已办
                queryflowRet = feignDemandService.searchInvolveUserProcessList(pageNumber, pageSize, paramSearchDto);
            } else {//查询全部（对于每个项目的管理员，则可以查看全部，否则只能看自己相关的或者同组人员的）
                if (demandService.beSystemManager(userDto.getUsername(), createProject)) {//系统的项目经理，查看全部
                    paramSearchDto.setStartUser(null);
                    paramSearchDto.setInvolveUser(null);
                    queryflowRet = feignDemandService.searchAllOrStartProcessList(pageNumber, pageSize, paramSearchDto);
                } else {//普通人员，限制只和自己有关以及同组发起流程
                    FlowableResponse<PageDataResult<ResponseSituationDto>> involveUserProcessListAll = feignDemandService.searchInvolveUserProcessList(1, 10000, paramSearchDto);
                    PageDataResult<ResponseSituationDto> involveList = involveUserProcessListAll.getData();
                    if (CollectionUtil.isNotEmpty(involveList.getList())) {
                        List<String> deamProcessList = involveList.getList().stream().map(ResponseSituationDto::getProcessId).collect(Collectors.toList());
                        //如果前面的限制条件生效，则此处不再添加条件。避免前面的条件不生效
                        if (CollectionUtil.isNotEmpty(deamProcessList)) {
                            if (CollectionUtil.isEmpty(paramSearchDto.getProcessIdList())) {
                                paramSearchDto.setProcessIdList(deamProcessList);
                            } else if (paramSearchDto.getProcessIdList().stream().noneMatch(e -> e.equals(no_result))) {
                                paramSearchDto.getProcessIdList().addAll(deamProcessList);
                            }
                        } else {
                            paramSearchDto.setProcessIdList(ImmutableList.of(no_result));
                        }
                    }
                    queryflowRet = feignDemandService.searchAllOrStartProcessList(pageNumber, pageSize, paramSearchDto);
                }
            }

            // 接口返回失败
            if (queryflowRet.getStatus() != 0) {
                return PlatformResponse.failedMsg("操作失败", queryflowRet.getMsg());
            }

            List<ResponseSituationDto> list = queryflowRet.getData().getList();
            List<String> processIds = list.stream().map(ResponseSituationDto::getProcessId).collect(Collectors.toList());
            FlowableResponse<List<FlowableDemandDto>> demandinfos = feignDemandService.getDemandInfos(processIds);
            Map<String, FlowableDemandDto> demandDtoMap = demandinfos.getData().stream().collect(Collectors.toMap(FlowableDemandDto::getProcessInstanceId, t -> t));

            FlowableResponse<List<ResponseCommentDto>> nwret = feignDemandService.queryCommentsByProcessIds(processIds);

            Map<String, List<ResponseCommentDto>> CommentMap = nwret.getData().stream().collect(Collectors.groupingBy(ResponseCommentDto::getProcessInstanceId));

            // 结果类型转换
            List<DemandManagementDto> retdata = new ArrayList<DemandManagementDto>();
            for (ResponseSituationDto r : list) {

                DemandManagementDto nr = DemandManagementDto.instance(r);

                //调用网关接口查询具体要素信息
                FlowableDemandDto demandinfoDto = demandDtoMap.get(r.getProcessId());
                if (demandinfoDto != null) {
                    CommonUtils.copyPropertiesIgnoreNullOrEmptyString(nr, demandinfoDto);
                    nr.setCreateProject(demandinfoDto.getSystemId());
                    nr.setRqType(RqType.getRqType(demandinfoDto.getDemandType()));
                    nr.setRqDesc(demandinfoDto.getDemandDetail());
                    nr.setOriRqStaffName(demandinfoDto.getOriginalStaffName());
                    nr.setOriRqStaff(demandinfoDto.getOriginalStaff());
                    nr.setRqDepartment(demandinfoDto.getDepartment());

                    FlowableResponse<FlowableDemandDto> demandinfo = new FlowableResponse<FlowableDemandDto>(0, "", demandinfoDto);
                    if (demandinfo.getStatus() == 0) {
                        nr.setRqUgtLevel(demandinfo.getData().getDemandEmergeLevel() != null ? RqUgtLevel.getRqUgtLevel(demandinfo.getData().getDemandEmergeLevel()) : null);
                        if (!Strings.isNullOrEmpty(demandinfo.getData().getArrangeinfo())) {
                            try {
                                List<ArrangeInf> alist = JSONObject.parseArray(demandinfo.getData().getArrangeinfo(), ArrangeInf.class);
                                nr.setArrangeinfo(alist);
                            } catch (Exception e) {
                                logger.error("Arrangeinfo字符串转对象异常，请查看！流程继续。", e);
                            }
                        }
                        if (!Strings.isNullOrEmpty(demandinfo.getData().getOnlineinfo())) {
                            try {
                                List<OnlineInf> olist = JSONObject.parseArray(demandinfo.getData().getOnlineinfo(), OnlineInf.class);
                                nr.setOnlineinfo(olist);
                            } catch (Exception e) {
                                logger.error("OnlineInf字符串转对象异常，请查看！流程继续。", e);
                            }
                        }
                        nr.setComments(CommentMap.get(r.getProcessId()));
                    }
                }
                retdata.add(nr);
            }

            Pageable pageable = PageRequest.of(PageUtil.initPageNo(pageNumber) - 1, PageUtil.initPageSize(pageSize));
            Page<DemandManagementDto> retd = new PageImpl(retdata, pageable, queryflowRet.getData().getTotals());
            return PlatformResponse.successData(retd);
        } catch (Exception e) {
            logger.error("需求管理查询接口异常！", e);
            return PlatformResponse.failedMsg("操作失败", e.getMessage());
        }
    }

    @ApiOperation(value = "流程分页查询-调试", notes = "流程分页查询")
    @RequestMapping("/export")
    public byte[] export(HttpServletRequest request, @RequestBody DemandQueryExportParamDto param, HttpServletResponse response) throws IOException {
        response.setHeader("Content-Disposition", "attachment;" + "filename=" + URLEncoder.encode(ReportFileConfigEnum.EVENT_FLOW.getFileName(), "UTF-8"));
        String operatorStart = requestTool.getAccountFromRequest();
        PlatformResponse<Page<DemandManagementDto>> queryResp = this.listRq(request, 1, Integer.MAX_VALUE, param.getUserId(),
                param.getDemandDetail(), param.getShowSameDepartment(), param.getRqListType(), param.getTitle(), param.getBeginDate(), param.getEndDate(), param.getFinishFlag(), param.getCreateProject(),
                param.getVcStaff(), param.getVcOriginalStaff(), param.getDevUserId(), param.getDealUser(), param.getArchived());
        if (queryResp.isFailed()) {
            throw PlatformException.error("操作失败");
        }
        if (Objects.isNull(queryResp.getData()) || CollectionUtil.isEmpty(queryResp.getData().getContent())) {
            throw PlatformException.error("未找到数据", false, false);
        }
        List<DemandManagementDto> data = queryResp.getData().getContent();

        if (CollectionUtils.isEmpty(data)) {
            throw PlatformException.error("未找到数据", false, false);
        }
        Map<String, String> sysMap = mysqlDataDictionaryRepository.findByFieldName("SYSTEM_ID").stream().collect(Collectors.toMap(MysqlDataDictionary::getfCode, MysqlDataDictionary::getfValues));
        FlowableResponse<List<FlowableDemandDto>> resp = feignDemandService.getDemandInfos(data.stream().map(DemandManagementDto::getRqId).collect(Collectors.toList()));
        Map<String, FlowableDemandDto> demandDtoMap;
        if (CollectionUtils.isEmpty(resp.getData())) {
            demandDtoMap = Collections.EMPTY_MAP;
            logger.error("未找到需求流程数据");
        } else {
            demandDtoMap = resp.getData().stream().collect(Collectors.toMap(FlowableDemandDto::getProcessInstanceId, d -> d));
        }
        List<DemandManagementExportDto> exportDtoList = data.stream()
                .map(d -> {
                            DemandManagementExportDto build = DemandManagementExportDto.builder()
                                    .title(d.getTitle())
                                    .rqStaffCName(d.getRqStaffCName())
                                    .oriRqStaffName(d.getOriRqStaffName())
                                    .rqDesc(d.getRqDesc())
                                    .rqDepartment(Optional.ofNullable(demandDtoMap.get(d.getRqId())).map(FlowableDemandDto::getDepartment).orElse(StringUtils.EMPTY))
                                    .startDateTime(d.getStartDateTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")))
                                    .solution(Optional.ofNullable(demandDtoMap.get(d.getRqId())).map(FlowableDemandDto::getSolutionGeneral).orElse(StringUtils.EMPTY))
                                    .createProject(sysMap.getOrDefault(d.getCreateProject(), StringUtils.EMPTY))
                                    .rqUgtLevel(Objects.isNull(d.getRqUgtLevel()) ? StringUtils.EMPTY : d.getRqUgtLevel().getDesc())
                                    .rqType(Objects.isNull(d.getRqType()) ? StringUtils.EMPTY : d.getRqType().getDesc())
                                    .build();
                            if (CollectionUtil.isNotEmpty(d.getArrangeinfo())) {
                                int arrSize = d.getArrangeinfo().size();
                                if (arrSize == 1) {
                                    ArrangeInf arrInfo = d.getArrangeinfo().get(0);
                                    build.setDevUserName(Optional.ofNullable(arrInfo.getDevUserName()).orElse(StringUtils.EMPTY));
                                    build.setTaskDesc(Optional.ofNullable(arrInfo.getTaskDesc()).orElse(StringUtils.EMPTY));
                                    build.setEstiOnlineDate(Optional.ofNullable(arrInfo.getEstiOnlineDate()).map(LocalDate::toString).orElse(StringUtils.EMPTY));
                                } else {
                                    StringBuilder devUserSb = new StringBuilder(), taskDescSb = new StringBuilder(), onlineDateSb = new StringBuilder();
                                    for (int idx = 0; idx < arrSize; idx++) {
                                        ArrangeInf a = d.getArrangeinfo().get(idx);
                                        devUserSb.append(idx).append("）").append(Optional.ofNullable(a.getDevUserName()).orElse(StringUtils.EMPTY)).append(idx == arrSize - 1 ? StringUtils.EMPTY : "\r\n");
                                        taskDescSb.append(idx).append("）").append(Optional.ofNullable(a.getTaskDesc()).orElse(StringUtils.EMPTY)).append(idx == arrSize - 1 ? StringUtils.EMPTY : "\r\n");
                                        onlineDateSb.append(idx).append("）").append(Optional.ofNullable(a.getEstiOnlineDate()).map(LocalDate::toString).orElse(StringUtils.EMPTY)).append(idx == arrSize - 1 ? StringUtils.EMPTY : "\r\n");
                                    }
                                    build.setDevUserName(devUserSb.toString());
                                    build.setTaskDesc(taskDescSb.toString());
                                    build.setEstiOnlineDate(onlineDateSb.toString());
                                }
                            }
                            if (CollectionUtil.isNotEmpty(d.getOnlineinfo())) {
                                int onlineSize = d.getOnlineinfo().size();
                                if (onlineSize == 1) {
                                    OnlineInf onlineInfo = d.getOnlineinfo().get(0);
                                    build.setDevUserNameOnline(Optional.ofNullable(onlineInfo.getDevUserName()).orElse(StringUtils.EMPTY));
                                    build.setStartDevDate(Optional.ofNullable(onlineInfo.getStartDevDate()).map(LocalDate::toString).orElse(StringUtils.EMPTY));
                                    build.setEndDevDate(Optional.ofNullable(onlineInfo.getEndDevDate()).map(LocalDate::toString).orElse(StringUtils.EMPTY));
                                    build.setActualOnlineDate(Optional.ofNullable(onlineInfo.getActualOnlineDate()).map(LocalDate::toString).orElse(StringUtils.EMPTY));
                                } else {
                                    StringBuilder devUserOnlineSb = new StringBuilder(), startDateSb = new StringBuilder(), endDateSb = new StringBuilder(), actOnlineSb = new StringBuilder();
                                    for (int idx = 0; idx < onlineSize; idx++) {
                                        OnlineInf a = d.getOnlineinfo().get(idx);
                                        devUserOnlineSb.append(idx).append("）").append(Optional.ofNullable(a.getDevUserName()).orElse(StringUtils.EMPTY)).append(idx == onlineSize - 1 ? StringUtils.EMPTY : "\r\n");
                                        startDateSb.append(idx).append("）").append(Optional.ofNullable(a.getStartDevDate()).map(LocalDate::toString).orElse(StringUtils.EMPTY)).append(idx == onlineSize - 1 ? StringUtils.EMPTY : "\r\n");
                                        endDateSb.append(idx).append("）").append(Optional.ofNullable(a.getEndDevDate()).map(LocalDate::toString).orElse(StringUtils.EMPTY)).append(idx == onlineSize - 1 ? StringUtils.EMPTY : "\r\n");
                                        actOnlineSb.append(idx).append("）").append(Optional.ofNullable(a.getActualOnlineDate()).map(LocalDate::toString).orElse(StringUtils.EMPTY)).append(idx == onlineSize - 1 ? StringUtils.EMPTY : "\r\n");
                                    }
                                    build.setDevUserNameOnline(devUserOnlineSb.toString());
                                    build.setStartDevDate(startDateSb.toString());
                                    build.setEndDevDate(endDateSb.toString());
                                    build.setActualOnlineDate(actOnlineSb.toString());
                                }
                            }
                            return build;
                        }
                )
                .collect(Collectors.toList());
        return ReportFileUtil.export(exportDtoList, ReportFileConfigEnum.DEMAND_EXPORT);
    }

    /**
     * 通过查询当前任务人全部的processlist，废弃此方法
     *
     * @param queryflowRet
     * @param dealUser
     * @param pageNumber
     * @param pageSize
     * @param paramSearchDto
     * @return
     */
    private FlowableResponse<PageDataResult<ResponseSituationDto>> filterdealUserWithPage(FlowableResponse<PageDataResult<ResponseSituationDto>> queryflowRet, String dealUser, Integer pageNumber, Integer pageSize, ParamSearchDto paramSearchDto) {
        if (queryflowRet.getStatus() != 0) {
            throw new PlatformException(-1, queryflowRet.getMsg(), null);
        }
        if (StringUtils.isNotEmpty(dealUser)) {
            List<ResponseSituationDto> listAll = new ArrayList<>();
            PageDataResult<ResponseSituationDto> pageDataResult = queryflowRet.getData();
            int total = pageDataResult.getTotals();
//            int nowPageNumber = pageNumber;
            int querySize = 100;
            for (int i = 1; i <= Integer.valueOf(total / querySize) + 1; i++) {
                FlowableResponse<PageDataResult<ResponseSituationDto>> tmpResult = feignDemandService.searchAllOrStartProcessList(i, querySize, paramSearchDto);
                listAll.addAll(tmpResult.getData().getList());
            }
            List<ResponseSituationDto> filteredResult = listAll.stream().filter(e -> dealUser.equals(e.getCurrentAssignee())).collect(Collectors.toList());
//            if (filteredResult.size()>(pageNumber-1)*pageSize){
//                filteredResult = filteredResult.subList((pageNumber-1)*pageSize,pageNumber*pageSize > filteredResult.size() ? filteredResult.size() : pageNumber*pageSize);
//            }else {
//                filteredResult = new ArrayList<>();
//            }
            PageDataResult pageDataResultNew = new PageDataResult(pageNumber, pageSize, filteredResult);
            return FlowableResponse.success(pageDataResultNew);
        }
        return queryflowRet;
    }


    /**
     * 查询需求完整信息，包括业务要素信息及节点状态信息
     */
    @RequestMapping(method = RequestMethod.GET, value = "getProcessinfo")
    public PlatformResponse<AllProcessInfo> getProcessinfo(@RequestParam(value = "rqId", required = true) String rqId) {
        PlatformResponse<AllProcessInfo> ret;

        try {
            //1.获取流程信息
            FlowableResponse<ResponseSituationDto> processinfo = feignDemandService.getProcessInfo(rqId);
            if (processinfo.getStatus() != 0) {
                return PlatformResponse.failedMsg("操作失败", processinfo.getMsg());
            }

            //2.获取要素信息
            FlowableResponse<FlowableDemandDto> demandinfo = feignDemandService.getDemandInfo(rqId);
            if (demandinfo.getStatus() != 0) {
                return PlatformResponse.failedMsg("操作失败", demandinfo.getMsg());
            }

            AllProcessInfo info = new AllProcessInfo();

            //3.分析流程图信息
            //3.1将走过的节点加入AllProcessInfo
            processinfo.getData().getCreatedTaskInfoDtoList().forEach(r -> {
                info.addNode(r);
            });

            //3.2将没有走过的节点加入AllProcessInfo
            for (ProcessNode node : ProcessNode.values()) {
                if (!info.getFlowmap().containsKey(node)) {
                    info.addNullNode(node);
                }
            }

            //要素信息对象转换
            info.setGlRequirement(DemandManagementDto.instance(processinfo.getData(), demandinfo.getData()));

            //获取comments信息
            ParamCommentDto param = new ParamCommentDto();
            param.setProcessId(rqId);
            FlowableResponse<PageDataResult<ResponseCommentDto>> nwret = feignDemandService.queryCommentsByProcessId(1, 100, param);
            info.setComments(nwret.getData().getList());

            ret = PlatformResponse.successData(info);

        } catch (Exception e) {
            ret = PlatformResponse.failedMsg("操作失败", e.getMessage());
            logger.error("getProcessinfo异常！", e);
        }

        return ret;
    }


    /**
     * 更新需求紧急状态
     */
    @RequestMapping(method = RequestMethod.POST, value = "changeRqUgtLevel")
    public PlatformResponse<?> changeRqLevel(HttpServletRequest request, @RequestBody ChangeRqLevelRequest changeRqLevelReq) {
        PlatformResponse<?> ret;
        try {

            //2.更新级别
            FlowableResponse flowableResponse = feignDemandService.updateEmergeLevel(changeRqLevelReq.getRqId(), changeRqLevelReq.getRqUgtLevel().getNwCode());
            return flowableResponse.getStatus() == 0 ? PlatformResponse.success() : PlatformResponse.failedMsg("操作失败", flowableResponse.getMsg());
        } catch (Exception e) {
            logger.error("changeRqLevel异常！", e);
            return PlatformResponse.failedMsg("操作失败", e.getMessage());
        }
    }

    /**
     * 取消流程
     */
    @RequestMapping(method = RequestMethod.POST, value = "stopProcess")
    public PlatformResponse<?> stopProcess(HttpServletRequest request, @RequestBody String rqId) {
        PlatformResponse<?> ret;
        try {
            feignDemandService.stopProcessInstanceById(rqId, requestTool.getAccountFromRequest());
            return PlatformResponse.success();
        } catch (Exception e) {
            logger.error("stopProcess异常！", e);
            return PlatformResponse.failedMsg("操作失败", e.getMessage());
        }
    }


    @RequestMapping(method = RequestMethod.POST, value = "uploadDoc")
    public PlatformResponse<List<Map<String, String>>> uploadDoc(HttpServletRequest request, @RequestPart(value = "file") MultipartFile[] file) {
        PlatformResponse<List<Map<String, String>>> ret;
        try {
            //1.调用网关系统上传文件
            FlowableResponse<ResponseUploadDto> nwret = feignDemandService.uploadDoc(file);
            if (nwret.getStatus() == 0) {
                //"annexId": "http://10.1.81.200:12580/flowable/common/oaDownloadAppendix/ee7ded5a-2198-4d56-a44d-b2af055e227d",
                //"annexName": "需求测试文档.docx"
                List<Map<String, String>> list = nwret.getData().getFileList();
                list.forEach(r -> {
                    r.put("annexId", r.get("annexId").substring(r.get("annexId").lastIndexOf("/") + 1));
                });
                return PlatformResponse.successData(list);
            } else {
                return PlatformResponse.failedMsg("操作失败", nwret.getMsg());
            }
        } catch (Exception e) {
            logger.error("uploadDoc异常！", e);
            return PlatformResponse.failedMsg("操作失败", e.getMessage());
        }
    }


    @RequestMapping(method = RequestMethod.GET, value = "downloadDoc")
    public PlatformResponse<byte[]> downloadDoc(@RequestParam(value = "appendixId", required = true) String appendixId) {
        PlatformResponse<byte[]> ret;

        try {
            ResponseEntity<byte[]> nwret = feignDemandService.downloadDemandAppendix(appendixId);
            if (nwret != null) {
                ret = PlatformResponse.successData(nwret.getBody());
            } else {
                ret = PlatformResponse.failedMsg("文件下载失败");
            }

        } catch (Exception e) {
            ret = PlatformResponse.failedMsg("操作失败", e.getMessage());
            logger.error("downloadDoc异常！", e);
        }

        return ret;
    }

    @RequestMapping(method = RequestMethod.GET, value = "showDoc")
    public PlatformResponse<ReportShowResponse> show(@RequestParam(value = "appendixId", required = true) String appendixId,
                                                     @RequestParam(value = "appendixName", required = true) String appendixName) {
        PlatformResponse<ReportShowResponse> ret;
        try {
            String title = appendixName;
            String url = downloadUrl + appendixId;
            String token = tokenUtil.generateToken(JsonUtil.Obj2Str(new ReportShowResponse(title, url, FileType.valueOf(appendixName.substring(appendixName.lastIndexOf(".") + 1)))));

            ReportShowResponse resdata = new ReportShowResponse(title, url, token, FileType.valueOf(appendixName.substring(appendixName.lastIndexOf(".") + 1)));
            ret = PlatformResponse.successData(resdata);
            ret.setFileId(title);
        } catch (Exception e) {
            ret = PlatformResponse.failedMsg("操作失败", e.getMessage());
        }

        return ret;
    }

    /**
     * OA需求相关流程汇总查询
     *
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "pageOaDemandFlow")
    public PlatformResponse<Page<OaDemandFlowSumDto>> pageOaDemandFlow(@RequestBody OaDemandFlowSumQueryDto queryDto) {

        Page<OaDemandFlowSumDto> page = oaDemandFlowSumService.findPage(queryDto);
        return PlatformResponse.successData(page);
    }

}
